﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.UI;
using AVISOutBound.SSOServer.Orders.Dto;
using AVISOutBound.SSOServer.Payment.Dto;

namespace AVISOutBound.SSOServer.Orders
{
    /// <summary>
    /// 订单服务
    /// </summary>
    public class OrderAppService: ApplicationService,IOrderAppService
    {
        private IOrderRepository _orderRepository;

        private IOrderManager _orderManager;

        public OrderAppService(IOrderRepository orderRepository,IOrderManager orderManager)
        {
            _orderRepository = orderRepository;
            _orderManager = orderManager;
        }

        /// <summary>
        /// 关闭订单
        /// </summary>
        /// <param name="orderNo">订单号</param>
        /// <returns></returns>
        public async Task Close(string orderNo)
        {
            var order = this._orderManager.GetDBOrder(orderNo);
            await CloseOrder(order);
        }

        /// <summary>
        /// 自动关闭订单
        /// </summary>
        /// <returns></returns>
        public async Task AutoClose()
        {
            var orders = this._orderRepository.GetExpiredOrders();
            foreach (var order in orders)
            {
                await Close(order);
            }
        }

        /// <summary>
        /// 关闭订单
        /// </summary>
        /// <param name="order">订单</param>
        /// <returns></returns>
        protected async Task CloseOrder(Order order)
        {
            if (order == null)
            {
                throw new UserFriendlyException("订单不存在");
            }

            if (order.OrderStatus == (int) OrderStatus.Payed)
            {
                throw new UserFriendlyException("订单已支付，无法关闭");
            }

            if (order.IsCancel || order.OrderStatus == (int) OrderStatus.Cancel)
            {
                throw new UserFriendlyException("订单已取消");
            }

            order.OrderStatus = (int) OrderStatus.Cancel;
            order.IsCancel = true;

            await this._orderRepository.UpdateOrderStatus(order);
        }

        /// <summary>
        /// 更新备注
        /// </summary>
        /// <param name="input">设置备注输入参数</param>
        /// <returns></returns>
        public async Task UpdateRemark(SetRemarkInput input)
        {
            var order = this._orderManager.GetDBOrder(input.OrderNo);
            if (order == null)
            {
                throw new UserFriendlyException("订单不存在");
            }

            await this._orderRepository.UpdateRemark(input.OrderNo, input.Remark);
        }
    }
}
